import React, { Component } from "react";
import { Slider, Overlay } from 'react-native-elements';
import { 
  Image,
  StyleSheet,
  Alert,
  Button,
  Text,
  TextInput,
  View,
  ImageBackground,
  Dimensions,
  ScrollView,  
  SafeAreaView,
  TouchableOpacity,
  NativeModules,
  NativeEventEmitter,
  DeviceEventEmitter
} from 'react-native';

// function Name(props) {
//     return <h1>网站名称：{props.name}</h1>;
// }
const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;
const OpenNativeModule = NativeModules.OpenNativeModule;

export default class PageFM extends Component {
  // static navigationOptions = ({ navigation }) => {
  //   return {
  //     title: navigation.state.params.title,
  //   };
  // };
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      loaded: false,
      btfmState: '00',
      volume: 1,
      state: '00',
      isVisible: false,
      fm: '104.5',
      inputFM: '',
      switchSrc: require('../assets/switch_sauna.png'),
    }
    this.saveBt = this.saveBt.bind(this);
    this.gobackBt = this.gobackBt.bind(this);
    this.switchBt = this.switchBt.bind(this);
    this.editBt = this.editBt.bind(this);
    this.changeFM = this.changeFM.bind(this);
    this.minusBt = this.minusBt.bind(this);
    this.addBt = this.addBt.bind(this);
    this.volminusBt = this.volminusBt.bind(this);
    this.voladdBt = this.voladdBt.bind(this);
  }

  componentDidMount() {
    console.log('设备宽高')
    console.log(SCREEN_WIDTH)
    console.log(SCREEN_HEIGHT)
    this.state.btfmState=this.props.navigation.state.params.btfmState
   
    if(this.state.btfmState =='00' || this.state.btfmState == '02'){
      this.setState({
        switchSrc: require('../assets/switchoff_sauna.png')
      });
    } else {
      this.setState({
        switchSrc: require('../assets/switch_sauna.png')
      });
    }
    
    console.log(this.state.btfmState);

     //接收原生数据
     this.listener = null;
     if (Platform.OS === 'ios') {
       let eventEmitter = new NativeEventEmitter(OpenNativeModule);
       this.listener = eventEmitter.addListener("CustomEventName", (result) => {
         console.log(result);
         this.process(result)
       })
     } else {
       this.listener = DeviceEventEmitter.addListener("CustomEventName", (result) => {
         console.log(result);
         this.process(result)
       });
     }

    // btfmState = this.props.navigation.state.params.btfmState;
    // console.log(btfmState);
    // 接收原生数据并处理
    // 不要从主设备页面传参过来，如果用户在二级页面停留过久，也需要实时更新数据
  }
 
   // 处理实时状态数据
   process(res) {
    // 主开关
    // console.log(res.Device_SystemPower)
    console.log('处理广播页面数据');
    if (res.Device_SystemPower) {
      
    }
    
  }

  saveBt() {
    console.log('广播')
    
    var dataFMBTState
    volume = this.state.volume<10?'0'+this.state.volume.toString():this.state.volume.toString()
  
    console.log(volume)
    fm = (this.state.fm)*10;
    console.log(PrefixInteger(fm,4))
    if(this.state.btfmState == '00'|| this.state.btfmState == '02'){
      this.setState({
        btfmState : '01'
      });
      console.log("打开广播"+this.state.btfmState);
      dataFMBTState = {"data":{"deviceName":"Device_FMBT_StateFreqVol","value":'01'+PrefixInteger(fm.toString(16),4)+volume}}
    } else {
      this.setState({
        btfmState : '00'
      });
      console.log("关闭广播"+this.state.btfmState);
      dataFMBTState = {"data":{"deviceName":"Device_FMBT_StateFreqVol","value":'00'+PrefixInteger(fm.toString(16),4)+volume}}
    }
    
    OpenNativeModule.jump2Native(dataFMBTState).then((result) => {
      console.log(result);
    }).catch((error) => {
      console.log(error);
      Alert.alert(
        '提示',
        '命令发送失败！',
        [
          {text: '确认', onPress: () => console.log('OK Pressed')},
        ]
      )
    })
    console.log('保存用户设置')
    // 组合数据，发送指令
  }
  gobackBt() {
    console.log('返回主页')
    this.props.navigation.goBack()
    // this.props.navigation.navigate('Main')
  }
  minusBt() {
    // 频率减
    if(this.state.fm<=87.5){
      this.setState({
        fm:87.5
      }) 
    }else{
      this.setState({
       fm: ((parseInt(this.state.fm*10) - 1)/10).toString()
      });
    }
    console.log(this.state.fm)
  }
  addBt() {
    // 频率加
    if(this.state.fm>=108){
      this.setState({
        fm:108
      }) 
    }else{
      this.setState({
        fm: ((parseInt(this.state.fm*10) + 1)/10).toString()
      });
    }
    console.log(this.state.fm)
  }
  volminusBt() {
    // 音量减
    if(this.state.volume==0){

    }else {
      this.setState({ 
        volume: (this.state.volume - 1)
      });
    }
  }
  voladdBt() {
    // 音量加
    if(this.state.volume==10){

    }else{
      this.setState({
        volume: (this.state.volume + 1)
      });
    }
  }
  switchBt() {
    console.log('控制开关')
    if (this.state.state == '00') {
      this.setState({
        switchSrc: require('../assets/switch_sauna.png'),
        state: '01'
      });
    } else {
      this.setState({
        switchSrc: require('../assets/switchoff_sauna.png'),
        state: '00'
      });
    }
  }
  editBt() {
    this.setState({
      isVisible: true,
      inputFM: this.state.fm
    });
  }
  changeFM() {
    if(this.state.inputFM<=87.5){
      this.setState({
        fm: '87.5',
        isVisible: false
      });
    }else if (this.state.inputFM<=108){
      this.setState({
        fm: this.state.inputFM,
        isVisible: false
      });
    }else{
      this.setState({
        fm: '108',
        isVisible: false
      });
    }
    
  }

  render() {
    return (
      // <View>
      //   <Text>{this.props.navigation.state.params.title}</Text>
      //   <Text onPress={() => this.props.navigation.navigate('Main')}>点击跳转主页面</Text>
      //   <Text onPress={() => this.props.navigation.goBack()}>点击返回</Text>
      // </View>
      <SafeAreaView style={{ flex: 1 }}>
        <ScrollView contentContainerStyle={{ height: SCREEN_HEIGHT }}>
          <ImageBackground source={require('../assets/bg1.png')} style={styles.bgImage}>
            <View style={styles.header}>
              <View style={{ width: 70 }}>
                <TouchableOpacity onPress={this.gobackBt}>
                  <Image
                    source={require('../assets/icon_left.png')}
                    style={{ width:11, height:19, marginLeft:14 }}
                  />
                </TouchableOpacity>
              </View>
              <View style={{ flex: 1, alignItems: 'center' }}>
                <Text style={{ fontSize: 20, color:'#fff' } }>广播设置</Text>
              </View>
              <View style={{ width: 60 }}>
                <TouchableOpacity onPress={this.saveBt} style={styles.btn}>
                  <Text style={styles.btn_text}>保存</Text>
                </TouchableOpacity>
              </View>
              <View style={{ width: 10 }}>
              </View>
            </View>
            <View style={{ marginTop: 50, alignItems: 'center' }}>
              <Text style={{ fontSize: 40, color:'#fff' } }>{this.state.fm} Hz</Text>
              <TouchableOpacity onPress={this.editBt}>
                <Image
                  source={require('../assets/edit.png')}
                  style={{ width: 20, height:20, marginTop:10 }}/>
              </TouchableOpacity>
            </View>
            <View style={styles.info_container}>
              <TouchableOpacity onPress={this.minusBt}>
                <Image
                  source={require('../assets/icon_minus.png')}
                  style={{ width: 32, height: 32 }}/>
              </TouchableOpacity>
              <TouchableOpacity onPress={this.addBt}>
                <Image
                  source={require('../assets/icon_add.png')}
                  style={{ width: 32, height: 32 }}/>
              </TouchableOpacity>
            </View>
            <View style={{ alignItems: 'center', marginTop:30 } }>
              <TouchableOpacity onPress={this.switchBt}>
                <Image
                  source={this.state.switchSrc}
                  style={{ width:100, height:100, marginTop:30 }}
                />
              </TouchableOpacity>
            </View> 
            <View style={styles.volume}>
              <View style={{ flexDirection: 'row',justifyContent: 'space-between' } }>
                <TouchableOpacity onPress={this.volminusBt}>
                  <Image
                    source={require('../assets/vol_min.png')}
                    style={{ width: 50, height: 27 }}/>
                </TouchableOpacity>
                <TouchableOpacity onPress={this.voladdBt}>
                  <Image
                    source={require('../assets/vol_add.png')}
                    style={{ width: 60, height: 27 }}/>
                </TouchableOpacity>
              </View>
              <Slider
                value={this.state.volume}
                maximumValue={10}
                maximumTrackTintColor="#3887E1"
                minimumTrackTintColor="#10E5E2"
                step={1}
                thumbTintColor="#CDC9C9"
                onValueChange={value => this.setState({ volume:value })}
              />
              <Text style={{ fontSize: 20 }}>音量: {this.state.volume}</Text>
            </View>
          </ImageBackground>
              {/* <View>
                <TouchableOpacity onPress={this.mainBt}>
                  <Image
                    source={this.state.mainBtnSrc}
                    style={{ width:80, height:80, marginTop:30 }}
                  />
                </TouchableOpacity>
              </View>  */}
        </ScrollView>
        <Overlay
          isVisible={this.state.isVisible}
          windowBackgroundColor="rgba(139,134,130,.5)"
          overlayBackgroundColor="#ffffff"
          width="auto"
          height="auto"
          borderRadius={5}
          onBackdropPress={() => this.setState({ isVisible: false })}>
          <View style={styles.Overlay_view}>
            <Text style={{fontSize:16}}>请输入频率：</Text>
            <TextInput
              style={styles.overlay_input}
              onChangeText={(value) => this.setState({inputFM:value})}
              value={this.state.inputFM}
            />
            <View style={styles.overlay_btns}>
              <Button
                onPress={() => this.setState({ isVisible: false })}
                title=" 取消 "
                color="#3887E1"
              />
              <Button
                onPress={this.changeFM}
                title=" 确定 "
                color="#3887E1"
              />
            </View>
          </View>
        </Overlay>
      </SafeAreaView>
    );
  }
}

var styles = StyleSheet.create({
  bgImage: {
    flex: 1,
    width: SCREEN_WIDTH,
    height: 320
  },
  top: {
    width: SCREEN_WIDTH,
    height: 320,
    backgroundColor: '#87CEFA'
  },
  header: {
    flexDirection: 'row',
    width: SCREEN_WIDTH,
    marginTop:33,
    justifyContent: 'center',
  },
  btn: {
    width: 55,
    height: 30,
    backgroundColor: '#fff',
    borderRadius: 3,
    justifyContent: 'center',
    alignItems: 'center',
  },
  btn_text: {
    fontSize: 16,
    color: '#1E90FF'
  },
  info_container: {
    marginLeft: 40,
    marginRight: 40,
    marginTop: 50,
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  info: {
    fontSize: 18,
    marginLeft: 5,
    color: '#fff'
  },
  volume: {
    width: SCREEN_WIDTH - 40,
    marginTop: 50,
    marginLeft: 20,
  },
  Overlay_view: {
    padding: 20,
    width: 220
  },
  overlay_input: {
    height: 30,
    borderColor: 'gray',
    borderWidth: 1,
    padding: 0,
    paddingLeft: 8,
    marginTop:10,
    marginBottom:20
  },
  overlay_btns: {
    flexDirection: 'row',
    justifyContent: 'space-around',
  }
});

function PrefixInteger(num, n) {
  return (Array(n).join(0) + num).slice(-n);
}